/*******************************************************************************
 * Copyright (c) 2013,  Paul Daniels
 *
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.hupu.jrs.components.jockeyjs

import android.annotation.SuppressLint
import android.util.Log
import android.webkit.WebView
import android.webkit.WebViewClient
import com.alibaba.fastjson.JSON
import com.hupu.jrs.components.jockeyjs.util.ForwardingWebViewClient
import java.net.URI
import java.net.URISyntaxException

@SuppressLint("SetJavaScriptEnabled")
internal class JockeyWebViewClient(val implementation: JockeyImpl) : ForwardingWebViewClient() {
    private var _delegate: WebViewClient? = null

    fun setDelegate(client: WebViewClient) {
        _delegate = client
    }

    public override fun delegate(): WebViewClient? {
        return _delegate
    }

    override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {

        if (delegate() != null && delegate()!!.shouldOverrideUrlLoading(view, url)) return true

        try {
            val uri = URI(url)

            if (isJockeyScheme(uri)) {
                processUri(view, uri)
                return true
            }
        } catch (e: URISyntaxException) {
            e.printStackTrace()
        } catch (e: HostValidationException) {
            e.printStackTrace()
            Log.e("Jockey", "The source of the event could not be validated!")
        }

        return false
    }

    fun isJockeyScheme(uri: URI): Boolean {
        return uri.scheme == "jockey" && uri.query != ""
    }

    @Throws(HostValidationException::class)
    fun processUri(view: WebView, uri: URI) {
        val parts = uri.path.replace("^\\/".toRegex(), "").split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        val host = uri.host

        val payload = checkPayload(JSON.parseObject(uri.query, JockeyWebViewPayload::class.java))

        if (parts.size > 0) {
            if (host == "event") {
                implementation.triggerEventFromWebView(view, payload)
            } else if (host == "callback") {
                implementation.triggerCallbackForMessage(Integer.parseInt(parts[0]))
            }
        }
    }

    @Throws(HostValidationException::class)
    fun checkPayload(fromJson: JockeyWebViewPayload): JockeyWebViewPayload {
        validateHost(fromJson.host!!)
        return fromJson
    }

    @Throws(HostValidationException::class)
    private fun validateHost(host: String) {
        implementation.validate(host)
    }
}